
# Pylint doesn't find pygments namespaces:
# pylint: disable-msg=E0611

"""

utils.py
========

Misc helper funcitions 
----------------------

Author: Rob Cakebread <cakebread@ gmail. com>

License  : New BSD (See COPYING)




"""

__docformat__ = 'restructuredtext'

import os
from cStringIO import StringIO
from xml.dom.ext import PrettyPrint
import xml.dom.minidom as minidom
from urlparse import urlparse

from configobj import ConfigObj
from pygments import highlight
from pygments.lexers import XmlLexer
from pygments.formatters import TerminalFormatter
from rdflib import ConjunctiveGraph


def serialize_n_three(xml):
    """
    Serialize as Notation 3
   
    @param: xml
    @type: string

    @return: string of N3
    """
    store = ConjunctiveGraph()
    triples = store.parse(xml, publicID=None, format="xml")
    print triples.serialize(format="n3")
    
def print_item(file_obj, no_format=False, no_highlight=False):
    """
    Print a Twine Item (RDF/XML)

    @param: file_obj
    @type: file object

    @param: no_format
    @type: boolean

    @param: no_highlight
    @type: boolean

    @returns: None
    """

    if no_format and no_highlight:
        #Just print it, no highlighting, no formatting
        print file_obj.read()
    elif not no_highlight and no_format:
        #Highlight, no indenting
        highlight_xml(file_obj.read(), True)
    elif not no_format and no_highlight:
        #Indenting, no highlighting
        pretty_print_xml(file_obj, True)
    else:
        #Format and highlight
        pretty_print_xml(file_obj)
        

def pretty_print_xml(text, no_highlight=False):
    """
    Prints nicely indented XML with optional sytax highlighting

    @param text: XML
    @type text: string
    @returns: None
    
    """
    doc = minidom.parse(text)
    file_obj = StringIO()
    PrettyPrint(doc, file_obj)
    if no_highlight:
        print file_obj.getvalue()
    else:
        print highlight_xml(file_obj.getvalue())

def highlight_xml(text, output=False):
    """Syntax highlited XML"""
    if output:
        print highlight(text, XmlLexer(), TerminalFormatter())
    else:
        return highlight(text, XmlLexer(), TerminalFormatter())

def get_user_passwd():
    """Return a tuple of (username, password)"""
    get_rcfile_path()
    config = ConfigObj(get_rcfile_path())
    return config['username'], config['password']

def get_entwine_dir():
    """Return path where we store config files and data"""
    twinedir = os.path.abspath(os.path.expanduser("~/.entwine"))
    if not os.path.exists(twinedir):
        os.mkdir(twinedir)
        template = """username = "twine_username"\npassword = "twine_password"
        """
        open("%s/entwinerc" % twinedir, "w").write(template)
    return twinedir

def get_rcfile_path():
    """Return path of rc config file"""
    return os.path.abspath("%s/entwinerc" % get_entwine_dir())

def get_base_path_url(my_path):
    """
    Returns base of a URL
    
    @param: my_path
    @type: string
    @return: string

    Example: http://example.com/some/longass/path/to/foo
    Returns: foo
    
    """
    return os.path.basename(urlparse(my_path).path)

def get_toplevel_path(my_path):
    """
    Returns 'top-level' directory used to keep track of authentication
    path levels

    @param: my_path
    @type: string
    @return: string


    Example: http://example.com/some/longass/path/to/foo
    Returns: http://example.com/some

    """
    parts = urlparse(my_path)
    return parts.scheme + "://" + parts.netloc + os.path.split(parts.path)[0]


